package cn.edu.xust.api.controller;


import cn.edu.xust.configuration.exception.Default200Exception;
import cn.edu.xust.configuration.exception.ErrorConstant;
import cn.edu.xust.entity.SysRoleEntity;
import cn.edu.xust.entity.SysUserEntity;
import cn.edu.xust.entity.SysUserroleEntity;
import cn.edu.xust.service.SysRoleService;
import cn.edu.xust.service.SysUserService;
import cn.edu.xust.service.SysUserroleService;
import cn.edu.xust.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;

/**
 * @author ufo
 * @email 2575829997@qq.com
 * @date 2022-09-06 17:32:09
 */
@RestController
@RequestMapping("/api/sysuserrole")
@Slf4j
public class ApiSysUserroleController {
    @Autowired
    private SysUserroleService sysUserroleService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;



    /**
     * 查询某个账户可管理的角色列表
     */
    @RequestMapping("/list")
    protected R list(@RequestBody JSONObject jsonObject) throws Default200Exception, IOException, ClassNotFoundException {

        Integer uid = jsonObject.getInteger("uid");
        //判断用户身份是否是管理员
        SysUserEntity user = sysUserService.getById(uid);
        if (user == null) {
            log.info("uid不存在:{}", uid);
            throw new Default200Exception(ErrorConstant.userpwd_not_exist);
        }
        boolean ismanger = "-1".equals(user.getUtype());
        List<SysRoleEntity> list=new ArrayList<>();

        //root直接拿所有角色
        if (ismanger) {
            list = sysRoleService.list();
        }
        //其他需要凭借uid去拿
        else {

            //一个uid能管理他下面所有uid的角色
            list= sysRoleService.getByMakerids(Collections.singletonList(uid));
        }

        return R.ok().put("data", list);
    }



    /**
     * 查询某个账户是什么角色列表
     */
    @RequestMapping("/actroles")
    public R actroles(@RequestBody JSONObject jsonObject) throws Default200Exception {
        Integer uid = jsonObject.getInteger("uid");
        //查询用户角色
        List<SysUserroleEntity> sysUserroleEntities = sysUserroleService.getByUid(uid);
        List<Integer> roleids = sysUserroleEntities.stream().map(SysUserroleEntity::getRoleid).collect(Collectors.toList());
        return R.ok().put("data", roleids);
    }


}
